<?php
	define("THIS_PAGE", "invoices");

	require_once($_SERVER["DOCUMENT_ROOT"] . "/../sys/libs/init.lib");
	include($_SERVER["DOCUMENT_ROOT"] . "/../sys/includes/adminheader.php");

	if (array_key_exists("submit", $_REQUEST) && strtolower($_REQUEST["submit"]) == "add") {
		if (isset($_REQUEST["addTerm"]) && !empty($_REQUEST["addTerm"])) {
			if ($db->insert("paymentterms", array("Terms" => $_REQUEST["addTerm"]))) {
				header("Location: " . $_SERVER["PHP_SELF"]);
			} else {
				$errors[] = "Unable to Save!";
			}
		}
	}

	if (array_key_exists("submit", $_REQUEST) && strtolower($_REQUEST["submit"]) == "save") {

		$invdate = new CBDate($_REQUEST["inv_date"], $config["Locale"]["php_date_fmt"]);
		$invdate = $invdate->toDBString();

		$duedate = new CBDate($_REQUEST["inv_duedate"], $config["Locale"]["php_date_fmt"]);
		$duedate = $duedate->toDBString();

		$savedata = array(
			"InvoiceNumber" => $_REQUEST["inv_invoicenumber"],
			"Date"			=> $invdate,
			"DueDate"		=> $duedate,
			"TermsID"		=> 1,
			"ClientID"		=> $_REQUEST["inv_client"]);

		$invoiceid = $db->insert("invoice", $savedata);

		if ($invoiceid) {
			foreach ($_REQUEST["item_itemid"]["New"] AS $key => $val){
					$itemsavedata = array(
						"InvoiceID" 	=> $invoiceid,
						"ItemID"		=> $_REQUEST["item_itemid"]["New"][$key],
						"Description"	=> ($_REQUEST["item_description"]["New"][$key] ? $_REQUEST["item_description"]["New"][$key] : "NULL"),
						"Quantity"		=> ($_REQUEST["item_quantity"]["New"][$key] ? $_REQUEST["item_quantity"]["New"][$key] : "NULL"),
						"AmountEach"	=> ($_REQUEST["item_amounteach"]["New"][$key] ? $_REQUEST["item_amounteach"]["New"][$key] : "NULL"),
						"TaxAmount"		=> ($_REQUEST["item_taxamount"]["New"][$key] ? $_REQUEST["item_taxamount"]["New"][$key] : "NULL")
					);
				if ($itemsavedata['ItemID'] != '') { 
					if (!$db->insert("item_invoice", $itemsavedata)) $errors[] = "Unable to Save!";
				}
			}

			// Handle the recurring invoices
			if (array_key_exists("repeat", $_REQUEST) && array_key_exists("until", $_REQUEST)) {

				$recursavedata = array();
				$until = new CBDate($_REQUEST["until"], $config["Locale"]["php_date_fmt"]);
				$recursavedata["Until"] = $until->toDBString("MySQL");

				switch ($_REQUEST["repeat"]) {
					case "Daily":
						$recursavedata["Daily"] = 1;
						break;
					case "Weekly":
						$recursavedata["Weekly"] = 1;
						break;
					case "Monthly":
						$recursavedata["Monthly"] = 1;
						break;
				}
				$recursavedata["invoiceid"] = $invoiceid;
				if (!$db->insert("recurrence", $recursavedata)) $errors[] = "Unable to save Recurring record.";
			}
		}
		if (empty($errors)) {
			$js[] = "confirmMessage('Saved Successfully');";
		}
	}

	print "<div class=\"pagebody\">";

	$items = $db->getarray($queries->productsList());

	$today = new CBDate(NULL, $config["Locale"]["php_date_fmt"]);

	$max = $db->get("SELECT MAX(id) + 1 AS id FROM invoice");

	if (!$max->id || empty($max->id)) $max->id = 1;
	$fy_label = $today->fiscalyear . "-" . $max->id;

	$nextweek = new CBDate(NULL, $config["Locale"]["php_date_fmt"]);
	$nextweek->addInterval("day", 7);

	$client_options = "";
	$clients = $db->getarray($queries->clientsSQL());

	$js[] = "billto = new Object(); \n";

	foreach ($clients as $key => $client) {
		$billto = $client->BillTo;
		str_replace("'", "", $billto);
		$js[] = "billto.id{$client->id} = \"{$billto}\"; \n";
		$client_options .= "\t\t<option value=\"{$client->id}\">{$client->BusinessName}</option>\n";
	}

	$lastcat = "";

	$js[] = "
		attachEventListener(document.getElementById('inv_client'), 'change', billTo, false);
		function billTo(event) {
			var billtofield = document.getElementById('billto');
			var clientList = document.getElementById('inv_client');
			var clientId = clientList.options[clientList.selectedIndex].value;
			var b = billto['id'+clientId];
			billtofield.value = b;
		}
	";

	$js[] = "

		function init() {
			myPanel = new YAHOO.widget.Panel('myPanel', { width:'320px', visible:false, constraintoviewport:true, fixedcenter:true } );
			myPanel.render();
			YAHOO.util.Event.addListener('addTerms', 'click', myPanel.show, myPanel, true);
		}

		YAHOO.util.Event.addListener(window, 'load', init);

	";

?>

<form name="add_invoice" method="post" action="<?php print $_SERVER["PHP_SELF"]; ?>">

<table width="100%" border="0" id="invoicetable">

<tr>
	<td>Bill To
		<select name="inv_client" id="inv_client"/>
			<option value="">Choose</option>
			<?php print $client_options; ?>
		</select>
	</td>
	<td>Repeat</td>
	<td>Until</td>
	<td>Payment Terms</td>
	<td>Date</td>
	<td>Due Date</td>
	<td>Invoice Number</td>
</tr>

<tr rowspan="8" valign="top">
	<td valign="top"><textarea name="billto" id="billto" rows="5" cols="30" readonly="readonly"></textarea></td>
	<td><select name="repeat">
			<option value="">Choose</option>
			<option value="Daily">Daily</option>
			<option value="Weekly">Weekly</option>
			<option value="Monthly">Monthly</option>
		</select></td>
	<td><input type="text" size="8" name="until" /></td>
	<td><select name="terms">
			<option value="">Choose</option>
<?php
		$terms = $db->getarray("SELECT * FROM paymentterms;");
		if ($terms) {
			foreach ($terms as $key => $term) {
				print "<option value=\"{$term->id}\">{$term->Term}</option>";
			}
		}
?>
		</select><img src="img/edit_add.png" border="0" id="addTerms" /></td>
	<td><input type="text" size="8" name="inv_date" value="<?php print $today->strdate; ?>" /></td>
	<td><input type="text" size="8" name="inv_duedate" value="<?php print $nextweek->strdate; ?>" /></td>
	<td><input type="text" size="8" name="inv_invoicenumber" value="<?php print $fy_label; ?>" /></td>
</tr>
</table>
<table>
<tr>
	<td width="15%">Item Select</td>
	<td width="35%">Item Description</td>
	<td width="5%">Qty</td>
	<td>Amount Each</td>
	<td>Tax</td>
	<td>Total</td>
</tr>

<tr id="0">
	<td>
	<select name="item_itemid[New][0]" id="item_itemid[New][0]">
		<option value="">Choose</option>
<?php

	$js[] = "items = new Object();";

	foreach ($items as $key => $item) {
		if ($lastcat !== $item->CategoryID) {
			print("\t<option value=\"\" >\t{$item->CategoryName}</option>\n");
		}

		$js[] = "
			items.id{$item->id} = new Object(); \n
			var desc = '".str_replace("'","", $item->DefaultDescription)."'
			items.id{$item->id}.Description = desc;
			items.id{$item->id}.Amount = '{$item->Amount}'; \n
			items.id{$item->id}.Tax = '{$item->TaxAmount}'; \n
		";

		print("\t<option value=\"{$item->id}\"> > {$item->Name}</option>\n");

		$lastcat = $item->CategoryID;
	}

	$js[] = "
	attachEventListener(document.getElementById('item_itemid[New][0]'), 'change', populateInvoice, false);
	attachEventListener(document.getElementById('item_itemid[New][0]'), 'change', cloneRow, false);
	attachEventListener(document.getElementById('item_quantity[New][0]'), 'change', updateTotal, false);
	attachEventListener(document.getElementById('exportas'), 'mouseover', cancelExportTimeout, false);
	attachEventListener(document.getElementById('exportas'), 'mouseout', hideExportTimeout, false);

	function populateInvoice(event) {
		var selectrow = event.target.id;
		var rowid = selectrow.substr(11);

		var description = document.getElementById('item_description' + rowid);
		var amount = document.getElementById('item_amounteach' + rowid);
		var taxamount = document.getElementById('item_taxamount' + rowid);
		var itemlist = document.getElementById('item_itemid' + rowid)
		var itemid = itemlist.options[itemlist.selectedIndex].value;

		if (itemid) {
			var item = items['id'+itemid];
			description.value = items['id'+itemid].Description;
			amount.value = items['id'+itemid].Amount;
			taxamount.value = items['id'+itemid].Tax;
		} else {
			description.value = '';
			amount.value = '';
			taxamount.values = '';
		}
	}
	
	function updateTotal(event) {
		if (event.target.id.substr(0,13) == 'item_quantity') {
			var rowid = event.target.id.substr(13);
		}

		var amount = document.getElementById('item_amounteach' + rowid);
		var quantity = document.getElementById('item_quantity' + rowid);
		var taxamount = document.getElementById('item_taxamount' + rowid);
		var total = document.getElementById('rowtotal' + rowid);

		var addTotal = parseFloat(((amount.value ? parseFloat(amount.value) : 0) + (taxamount.value ? parseFloat(taxamount.value) : taxamount.value)) * parseInt(quantity.value));

		total.value = addTotal;
	}
	
	";
?>

	</select>
	</td>
	<td><input type="text" id="item_description[New][0]" name="item_description[New][0]" /></td>
	<td><input type="text" id="item_quantity[New][0]" name="item_quantity[New][0]" /></td>
	<td><input type="text" id="item_amounteach[New][0]" name="item_amounteach[New][0]" /></td>
	<td><input type="text" id="item_taxamount[New][0]" name="item_taxamount[New][0]" /></td>
	<td><input type="text" id="rowtotal[New][0]" name="rowtotal[New][0]" /></td>
</tr>
</table>

<table width="100%" id="invoiceoptionstable">
<tr>
	<td><label for "email">Email to Client: <input type="checkbox" name="email" checked="checked" /></label></td>
	<td><input type="button" id="Export" value="Export" onclick="return exportAs(this);" /> <input type="submit" id="submit" name ="submit" value="Save" /></td>
</tr>
</table>

</form>
<div id="exportas" class="exportas">
Export As;<br />
<form name="exportas" action="admin_invoices_export.php" target="_blank">
<table>
    <tr>
        <td>
        	CSV: <input type="radio" name="exportas" value="csv" /><br />
			PDF: <input type="radio" name="exportas" value="pdf" /><br />
        </td>
        <td>
        	<input type="submit" name="submit" value="go" /></form>
        </td>
    </tr>
</table>
</div>

<?php
	include($_SERVER["DOCUMENT_ROOT"] . "/../sys/includes/adminfooter.php");
?>

